package com.gaocy.utils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * MD5 sign签名校验宇生成工具
 */
public class GenerateSignatureUtil {

    public static final String FIELD_SIGN = "sign";

    /**
     * 判断签名是否正确，必须包含sign字段，否则返回false。
     *
     * @param data Map类型数据
     * @param key  API密钥
     * @return 签名是否正确
     * @throws Exception
     */
    public static boolean isSignatureValid(Map<String, String> data, String key) {
        if (!data.containsKey(FIELD_SIGN)) {
            return false;
        }
        String sign = data.get(FIELD_SIGN);
        return generateSignature(data, key).equals(sign);
    }

    public static String generateSignature(final Map<String, String> data, String key) {
        try {
            Set<String> keySet = data.keySet();
            String[] keyArray = keySet.toArray(new String[keySet.size()]);
            Arrays.sort(keyArray);
            StringBuilder sb = new StringBuilder();
            for (String k : keyArray) {
                if (k.equals(FIELD_SIGN)) {
                    continue;
                }
                // 参数值为空，则不参与签名
                if (data.get(k).trim().length() > 0)  {
                    sb.append(k).append("=").append(data.get(k).trim()).append("&");
                }
            }
            //sb.append("key=").append(key);
            return MD5.md5(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) {

        /*
         * {"timestamp":"1660533153614",
         * "secret":"JYHS1yWXCW00ore71TXE4aDatAEN6j0G",
         * "token":"123","data":{"name":"bean","age":32}}
164ac196f52a1be61f8381b8e850876a
         **/
        Map<String, Object> data = new HashMap<>();
        Map<String, String> data1 = new HashMap<>();


        data1.put("name", "bean");
        data1.put("age", "32");

        data.put("timestamp", "1660533153614");
        data.put("secret", "JYHS1yWXCW00ore71TXE4aDatAEN6j0G");
        data.put("token", "123");
        data.put("data1",data1);

        data.put("sign", "164ac196f52a1be61f8381b8e850876a");
        String secret = "JYHS1yWXCW00ore71TXE4aDatAEN6j0G";
        //System.out.println(generateSignature(data, secret));
        //System.out.println("校验：" + isSignatureValid(data, secret));

    }

}
